import random

from PyQt5 import sip
from PyQt5.QtCore import QTimer, QSize
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QPushButton


class BaseButton(QPushButton):
    def __init__(self, normal_icon_path, hit_icon_path, speed=800, parent=None):
        super().__init__(parent)
        self.paused = None
        self.normal_icon_path = normal_icon_path
        self.hit_icon_path = hit_icon_path

        self.setFixedSize(100, 100)
        self.setIcon(QIcon(self.normal_icon_path))
        self.setIconSize(QSize(100, 100))

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.move_randomly)
        self.timer.start(speed)

        self.move_randomly()

    def move_randomly(self):
        parent = self.parent()
        if not parent:
            return
        max_x = parent.width() - self.width()
        max_y = parent.height() - self.height()
        for _ in range(100):
            x = random.randint(0, max_x)
            y = random.randint(100, max_y)
            self.move(x, y)
            return

    def cleanup(self):
        if self.timer:
            self.timer.stop()
            self.timer.deleteLater()
            self.timer = None
        self.hide()
        self.deleteLater()

    def pause(self):
        if self.timer is not None and not sip.isdeleted(self.timer):
            self.paused = True
            self.timer.stop()

    def resume(self):
        if self.timer is not None and not sip.isdeleted(self.timer):
            self.paused = False
            self.timer.start(800)


